package com.yunkaweilai.android.activity.member;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.model.AppRuleModel;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.member.MemberHeadModel;
import com.yunkaweilai.android.model.member.MemberInfoModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.dialog.member.MemberDelDialog;
import com.yunkaweilai.android.view.dialog.member.MemberStatusDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 会员详情
 * Created by Administrator on 2017/6/20.
 */

public class MemberInfoListActivity extends BaseActivity {
    public static final String MEMBER_MODEL = "MEMBER_MODEL";
    public static final String MEMBER_BUNDLE = "MEMBER_BUNDLE";
    @BindView(R.id.id_img_head)
    ImageView idImgHead;
    @BindView(R.id.id_tv_card_infor)
    TextView idTvCardInfor;
    @BindView(R.id.id_tv_name)
    TextView idTvName;
    @BindView(R.id.id_tv_lock)
    TextView idTvLock;
    @BindView(R.id.id_tv_report)
    TextView idTvReport;
    @BindView(R.id.id_tv_recharge)
    TextView idTvRecharge;
    @BindView(R.id.id_tv_changing_card)
    TextView idTvChangingCard;
    @BindView(R.id.id_tv_update_password)
    TextView idTvUpdatePassword;
    @BindView(R.id.id_tv_update)
    TextView idTvUpdate;
    @BindView(R.id.id_rl_info)
    RelativeLayout idRlInfo;
    @BindView(R.id.id_rl_consume)
    RelativeLayout idRlConsume;
    @BindView(R.id.id_rl_recharge)
    RelativeLayout idRLCecharge;
    @BindView(R.id.id_rl_residual_count)
    RelativeLayout idRlResidualCount;
    @BindView(R.id.id_rl_residual_time)
    RelativeLayout idRlResidualTime;
    @BindView(R.id.id_rl_residual_more_time)
    RelativeLayout idRlResidualMoreTime;
    @BindView(R.id.id_rl_stored_value)
    RelativeLayout idRlStoredValue;
    @BindView(R.id.id_rl_integral)
    RelativeLayout idRlIntegral;
    @BindView(R.id.id_rl_integral_exchange)
    RelativeLayout idRlIntegralExchange;
    @BindView(R.id.id_tv_del)
    TextView idTvDel;
    @BindView(R.id.member_line_bottom)
    LinearLayout mLinearLayoutbottom;
    @BindView(R.id.id_tv_consume_record)
    TextView idTvConsumeRecord;
    @BindView(R.id.id_tv_recharge_record)
    TextView idTvRechargeRecord;

    private MemberHeadModel model;
    private boolean member_status = true;
    private AppRuleModel.DataBean.InfoBean appRuleModel;
    private String Type = "1";

    public static void actionStart(Context context, MemberHeadModel model,String Type) {
        Intent intent = new Intent(context, MemberInfoListActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(MEMBER_MODEL, model);
        intent.putExtra(MEMBER_BUNDLE, bundle);
        intent.putExtra("TYPE",Type);
        context.startActivity(intent);
    }


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_member_info_list);
        ButterKnife.bind(this);
        appRuleModel = BaseApplication.getAppRuleModel();
        if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("18")) {
            mLinearLayoutbottom.setVisibility(View.VISIBLE);
        } else {
            mLinearLayoutbottom.setVisibility(View.GONE);
        }
        Intent intent = getIntent();
        model = (MemberHeadModel) intent.getBundleExtra(MEMBER_BUNDLE).getSerializable(MEMBER_MODEL);
        Type = intent.getStringExtra("TYPE");
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }


        initHeadView();
        if ("0".equals(model.getIs_password())) {
            idTvUpdatePassword.setVisibility(View.GONE);
        } else if ("1".equals(model.getIs_password())) {
            idTvUpdatePassword.setVisibility(View.VISIBLE);
        }
        //权限管理
        initView();

        getMemberHead();
//        if (model.getStatus_info().is_valid()) {
//            status_member(false, 1);
//        }


    }

    private void initQX() {
        if (Type.equals("1")&&model.getStatus_info().is_valid()) {
            status_member(false, 5);
        } else if ("1".equals(model.getMl_status())) {
            status_member(true, 0);
        } else if ("2".equals(model.getMl_status())) {
            status_member(false, 2);
        } else if ("3".equals(model.getMl_status())) {
            status_member(false, 3);
        }
    }

    //绿底白字
    @SuppressLint("ResourceAsColor")
    private void green(TextView textView) {
        textView.setClickable(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            textView.setBackground(getResources().getDrawable(R.drawable.selector_guadan_bg_new));
            textView.setTextColor(getResources().getColor(R.color.white));
        }
    }

    //灰底黑字
    @SuppressLint("ResourceAsColor")
    private void grey(TextView textView) {
        textView.setClickable(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            textView.setBackground(getResources().getDrawable(R.drawable.selector_guadan_bg2));
            textView.setTextColor(getResources().getColor(R.color.wjx_content_txt_light_black));
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void initView() {
        if (appRuleModel.isIs_super()) {
            green(idTvUpdate);
            green(idTvDel);
            green(idTvLock);
            green(idTvReport);
            green(idTvChangingCard);
            green(idTvUpdatePassword);
            green(idTvRecharge);
            initQX();
        } else {
            if (appRuleModel.getApp_rule().get("18")) {
                green(idTvUpdate);
                green(idTvDel);
                green(idTvLock);
                green(idTvReport);
                green(idTvChangingCard);
                green(idTvUpdatePassword);
                initQX();
            } else {
                grey(idTvUpdate);
                grey(idTvDel);
                grey(idTvLock);
                grey(idTvReport);
                grey(idTvChangingCard);
                grey(idTvUpdatePassword);
                if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("9")) {
                    green(idTvRecharge);
                } else {
                    grey(idTvRecharge);
                }
            }

        }


    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onShopEvent(Event.OtherTypeEvent event) {
        if (event != null) {
            if (event.type == CommonConstants.MEMBER_INFO_LIST) {
                if (event.flag) {
                    getMemberHead();
                }
            }
        }
    }


    private void getMemberHead() {
        HttpRequest.postUrl(Api.MEMBER_INFO_BASIC)
                .addParams("member_id", model.getId())
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean codeInfoRs = Utils.checkCode(mAc, json);
                        if (codeInfoRs) {
                            Gson gson = new Gson();
                            MemberInfoModel memberInfoModel = gson.fromJson(json, MemberInfoModel.class);
                            model = memberInfoModel.getData().getList();
                            //设置消费记录和充值记录
                            idTvConsumeRecord.setText("     消费次数：" + model.getTotal_order_count() + "      消费金额：" + model.getTotal_order_price());
                            idTvRechargeRecord.setText("     充值次数：" + model.getTotal_recharge_order_count() + "      充值金额：" + model.getTotal_recharge_order_price());
                            updateHead(model);
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                    }
                });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    private void updateHead(MemberHeadModel headModel) {
        idTvName.setText(headModel.getMember_name() + "(" + headModel.getLevel_name() + ": " + headModel.getCard_no() + ")");
        idTvCardInfor.setText("折扣：" + headModel.getDiscount() / 10 + "折   积分：" + headModel.getMember_points() + "   余额：" + headModel.getMember_price());
        if ("2".equals(headModel.getMl_status())) {
            idTvLock.setText("已锁定");
            idTvLock.setTextColor(getResources().getColor(R.color.white));
        } else if ("3".equals(headModel.getMl_status())) {
            idTvReport.setText("已挂失");
            idTvReport.setTextColor(getResources().getColor(R.color.white));
        }
    }

    //头部信息
    private void initHeadView() {
        new TitleBuilder(mAc).setTitleText("会员详情").setLeftImage(R.mipmap.ic_go_back)
                .setLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
        Utils.MemberHeadImg(mAc, model.getMember_avatar(), model.getMember_sex(), idImgHead);
        idTvName.setText(model.getMember_name() + " (" + model.getLevel_name() + ": " + model.getCard_no() + ")");
        idTvCardInfor.setText("折扣：" + model.getDiscount() / 10 + "折   积分：" + model.getMember_points() + "   余额：" + model.getMember_price());
        if ("2".equals(model.getMl_status())) {
            idTvLock.setText("已锁定");
            idTvLock.setTextColor(getResources().getColor(R.color.white));
        } else if ("3".equals(model.getMl_status())) {
            idTvReport.setText("已挂失");
            idTvReport.setTextColor(getResources().getColor(R.color.white));
        }

    }


    @OnClick({R.id.id_img_head, R.id.id_rl_info, R.id.id_rl_recharge, R.id.id_rl_consume, R.id.id_rl_residual_count, R.id.id_rl_residual_time, R.id.id_rl_residual_more_time, R.id.id_rl_stored_value, R.id.id_rl_integral, R.id.id_rl_integral_exchange, R.id.id_tv_update, R.id.id_tv_recharge, R.id.id_tv_update_password, R.id.id_tv_changing_card, R.id.id_tv_lock, R.id.id_tv_report, R.id.id_tv_del})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.id_img_head:
                Utils.ImageEnlage(mAc, "1", model.getMember_avatar(), model.getMember_sex());
                break;
            case R.id.id_rl_info://基本信息
                MemberInfoActivity.actionStart(mAc, model, "1");
                break;
            case R.id.id_rl_consume://消费记录
                ConsumeRecordActivity.actionStart(mAc, model);
                break;
            case R.id.id_rl_recharge://充值记录
                RechargeRecordActivity.actionStart(mAc, model);
                break;
            case R.id.id_rl_residual_count://剩余计次
                RemainingTimesActivity.actionStart(this, RemainingTimesActivity.COUNT_TYPE, model);
                break;
            case R.id.id_rl_residual_time://剩余计时
                RemainingTimesActivity.actionStart(this, RemainingTimesActivity.TIME_TYPE, model);
                break;
            case R.id.id_rl_residual_more_time://剩余包时段
                RemainingTimesActivity.actionStart(this, RemainingTimesActivity.MORE_TIME_TYPE, model);
                break;
            case R.id.id_rl_stored_value://储值变动
                StoredValueActivity.actionStart(this, model);
                break;
            case R.id.id_rl_integral://积分变动
                IntegralChangeActivity.actionStart(this, model);
                break;
            case R.id.id_rl_integral_exchange://积分兑换记录
                IntegralExchangeRecordActivity.actionStart(this, model);
                break;
            case R.id.id_tv_update://修改
                if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("18")) {
                    if (model != null && model.is_edit()) {
                        UpdateMemberInfoActivity.actionStart(mAc, model);
                    } else {
                        showToast(R.string.member_updata_tip);
                    }
                }
                break;
            case R.id.id_tv_recharge://充值
                if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("9")) {
                    if (member_status) {
                        if (model != null && "1".equals(model.getIs_stored())) {
                            MemberRechargeActivity.actionStart(this, model);
                        }
                    } else {
                        showToast("该卡暂时无法使用");
                    }
                } else {
                    showToast("无充值权限");
                }
                break;
            case R.id.id_tv_update_password://修改支付密码
                if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("18")) {
                    if (member_status) {
                        if (model.is_edit()) {
                            UpdatePayPasswordActivity.actionStart(mAc, model);
                        } else {
                            showToast(R.string.member_updata_tip);
                        }
                    } else {
                        showToast("该卡暂时无法使用");
                    }
                }
                break;
            case R.id.id_tv_changing_card://换卡
                if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("18")) {
                    if (member_status) {
                        if (model.is_edit()) {
                            MemberChangeCardActivity.actionStart(mAc, model);
                        } else {
                            showToast(R.string.member_updata_tip);
                        }
                    } else {
                        showToast("该卡暂时无法使用");
                    }
                }

                break;
            case R.id.id_tv_lock://锁定
                if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("18")) {
                    if (model.is_edit()) {
                        MemberStatusDialog dialog = null;
                        if ("1".equals(model.getMl_status())) {
                            dialog = new MemberStatusDialog(mAc, model, "lock", "确认锁定会员？", idTvLock, idTvReport);
                        } else if ("2".equals(model.getMl_status())) {
                            dialog = new MemberStatusDialog(mAc, model, "lock", "确认解除锁定会员？", idTvLock, idTvReport);
                        }
                        if (dialog != null) {
                            dialog.show();
                        }
                    } else {
                        showToast(R.string.member_updata_tip);
                    }
                }


                break;
            case R.id.id_tv_report://挂失
                if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("18")) {
                    if (model.is_edit()) {
                        MemberStatusDialog dialogs = null;
                        if ("1".equals(model.getMl_status())) {
                            dialogs = new MemberStatusDialog(mAc, model, "lost", "确认挂失会员？", idTvReport, idTvLock);
                        } else if ("3".equals(model.getMl_status())) {
                            dialogs = new MemberStatusDialog(mAc, model, "lost", "确认解除挂失会员？", idTvReport, idTvLock);
                        }
                        if (dialogs != null) {
                            dialogs.show();
                        }
                    } else {
                        showToast(R.string.member_updata_tip);
                    }
                }


                break;
            case R.id.id_tv_del://删除
                if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("18")) {
                    if (model.is_edit()) {
                        MemberDelDialog delDialog = new MemberDelDialog(mAc, model.getId());
                        delDialog.show();
                    } else {
                        showToast(R.string.member_updata_tip);
                    }
                }
                break;
        }
    }

    //该会员是否可用
    public void status_member(boolean flag, int type) {
        member_status = flag;
        if (member_status) {
            if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("9")) {
                green(idTvRecharge);
            } else {
                grey(idTvRecharge);
            }
            green(idTvChangingCard);
            green(idTvUpdatePassword);
        } else {
            if (appRuleModel.isIs_super() || appRuleModel.getApp_rule().get("9")) {
                grey(idTvRecharge);
            }
            grey(idTvChangingCard);
            grey(idTvUpdatePassword);
        }
        if (type == 0) {//都可以使用的时候
            green(idTvLock);
            green(idTvReport);
        } else if (type == 2) {//已锁定
            grey(idTvReport);
            grey(idTvRecharge);
            idTvLock.setClickable(true);
        } else if (type == 3) {//已挂失
            grey(idTvLock);
            grey(idTvRecharge);
            idTvReport.setClickable(true);
        } else if (type == 5) {
            grey(idTvRecharge);
            grey(idTvChangingCard);
            grey(idTvLock);
            grey(idTvReport);
            grey(idTvUpdatePassword);
        }
    }

}
